import pygame
from pygame.locals import *
from config import Config


class Hello:
    def __init__(self, screen, config):
        self.screen = screen
        self.config = config
        self.font = pygame.font.Font(self.config.font_path, 74)
        self.small_font = pygame.font.Font(self.config.font_path, 50)
        self.levels = ["开始关卡"]
        self.selected_level = 0
        self.background = pygame.image.load("images/background.png")

    def draw_welcome(self):
        """绘制欢迎界面"""
        self.screen.blit(self.background, (0, 0))  # 绘制背景
        welcome_text = self.font.render("欢迎来到弹球游戏！", True, self.config.colors['white'])
        self.screen.blit(welcome_text, (self.config.screen_width // 2 - 200, 100))  # 绘制标题

        # 绘制关卡选项
        for i, level in enumerate(self.levels):
            color = self.config.colors['white'] if i != self.selected_level else self.config.colors['red']
            level_text = self.small_font.render(level, True, color)
            text_width, text_height = level_text.get_size()
            text_x = (self.config.screen_width - text_width) // 2  # 水平居中
            text_y = 200 + i * 60  # 垂直位置保持不变
            self.screen.blit(level_text, (text_x, text_y))

    def handle_events(self):
        """处理用户输入事件"""
        for event in pygame.event.get():
            if event.type == QUIT:  # 退出事件
                pygame.quit()
                return False
            if event.type == MOUSEBUTTONDOWN:  # 鼠标点击事件
                mouse_pos = pygame.mouse.get_pos()
                for i, _ in enumerate(self.levels):
                    option_rect = pygame.Rect(
                        self.config.screen_width // 2 - 100, 200 + i * 60, 200, 50
                    )
                    if option_rect.collidepoint(mouse_pos):  # 检查点击位置
                        return i + 1  # 返回选择的关卡编号
            if event.type == MOUSEMOTION:  # 鼠标移动事件
                mouse_pos = pygame.mouse.get_pos()
                for i, _ in enumerate(self.levels):
                    option_rect = pygame.Rect(
                        self.config.screen_width // 2 - 100, 200 + i * 60, 200, 50
                    )
                    if option_rect.collidepoint(mouse_pos):  # 更新选中项
                        self.selected_level = i
        return True

    def run(self):
        """运行欢迎界面"""
        while True:
            self.screen.fill(self.config.colors['black'])  # 清空屏幕
            self.draw_welcome()  # 绘制界面
            pygame.display.flip()  # 更新显示

            result = self.handle_events()  # 处理事件
            if result is not True:
                return result
